const http = require('http');
const url = require('url');

http.createServer(function(req, res) {
  console.log('start request:', req.url);
  const options = url.parse(req.url);
  console.log(options);
  options.headers = req.headers;
  const proxyRequest = http.request(options, function(proxyResponse) { // 创建请求来复制原始的请求
    proxyResponse.on('data', function(chunk) { // 监听数据，返回给浏览器
      console.log('proxyResponse length:', chunk.length);
      res.write(chunk, 'binary');
    });

    proxyResponse.on('end', function() { // 追踪代理请求完成
      console.log('proxied request ended');
      res.end();
    });

    res.writeHead(proxyResponse.statusCode, proxyResponse.headers); // 发送头部信息给服务器
  });

  req.on('data', function(chunk) { // 捕获从浏览器发送到服务器的数据
    console.log('in request length:', chunk.length);
    proxyRequest.write(chunk, 'binary');
  });

  req.on('end', function() { // 追踪原始的请求什么时候结束
    console.log('original request ended');
    proxyRequest.end();
  });
}).listen(8888); // 监听来自本地浏览器的连接